package org.dreamland.infrastructure.security

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.OncePerRequestFilter

class SmartAuthFilter: OncePerRequestFilter() {

    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain
    ) {
        // 优先处理 JWT 认证
        request.getHeader("Authorization")
            ?.takeIf { it.startsWith("Bearer ") }?.substring(7)
            ?.let { JwtUtils.parseToken(it) }
            ?.let {
                SecurityContextHolder.getContext().authentication =
                    UsernamePasswordAuthenticationToken(it, null, it.authorities)
            }

        // 如果 JWT 认证失败则自动尝试 Session 认证
        filterChain.doFilter(request, response)
    }
}